package com.yuqih.common.spring;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import com.yuqih.common.exception.CodedException;

public class DateConverter implements Converter<String, Date> {
	
	public static final DateConverter instance = new DateConverter();
	
	private final SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private final Pattern patternTime = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$");
	
	private final SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
	private final Pattern patternDate = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2}$");

	@Override
	public Date convert(String source) {
		String value = StringUtils.trim(source);
		if (StringUtils.isBlank(value)) {
			return null;
		}
		try {
			long time = Long.valueOf(value);
			return new Date(time);
		} catch (NumberFormatException ignore) {
			
		}
		if (patternTime.matcher(value).matches()) {
			try {
				return sdfTime.parse(value);
			} catch (ParseException e) {
				throw CodedException.from(e);
			}
		} else if (patternDate.matcher(value).matches()) {
			try {
				return sdfDate.parse(value);
			} catch (ParseException e) {
				throw CodedException.from(e);
			}
		}
		throw new IllegalArgumentException("未知的日期格式：" + value);
	}
	
}
